from django.shortcuts import render

# Create your views here.
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponse
from .models import UserData
from pyecharts.charts import Bar
from pyecharts import options as opts
from django.shortcuts import render
from django.db.models import Q
import json



def home(request):
    if not request.user.is_authenticated:
        return redirect('login')
    return render(request, 'home.html')

def register(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        if User.objects.filter(username=username).exists():
            return render(request, 'register.html', {'error': '用户名已存在'})
        User.objects.create_user(username=username, password=password)
        return redirect('login')
    return render(request, 'register.html')

def user_login(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user:
            login(request, user)
            return redirect('home')
        else:
            return render(request, 'login.html', {'error': '用户名或密码错误'})
    return render(request, 'login.html')

def user_logout(request):
    logout(request)
    return redirect('login')

def data_list(request):
    if not request.user.is_authenticated:
        return redirect('login')
    data = UserData.objects.filter(user=request.user)
    return render(request, 'data_list.html', {'data': data})

def data_add(request):
    if request.method == 'POST':
        title = request.POST['title']
        content = request.POST['content']
        UserData.objects.create(user=request.user, title=title, content=content)
        return redirect('data_list')
    return render(request, 'data_add.html')

def data_edit(request, data_id):
    record = UserData.objects.get(id=data_id, user=request.user)
    if request.method == 'POST':
        record.title = request.POST['title']
        record.content = request.POST['content']
        record.save()
        return redirect('data_list')
    return render(request, 'data_edit.html', {'record': record})

def data_delete(request, data_id):
    record = UserData.objects.get(id=data_id, user=request.user)
    record.delete()
    return redirect('data_list')

def export_json(request):
    if not request.user.is_authenticated:
        return redirect('login')

    user_data = UserData.objects.filter(user=request.user)
    export_list = [
        {
            "title": item.title,
            "content": item.content,
            "created_at": item.created_at.strftime("%Y-%m-%d %H:%M:%S")
        } for item in user_data
    ]

    response = HttpResponse(
        json.dumps(export_list, ensure_ascii=False, indent=4),
        content_type='application/json'
    )
    response['Content-Disposition'] = 'attachment; filename="my_data.json"'
    return response

import json
from django.core.files.storage import default_storage

def import_json(request):
    if not request.user.is_authenticated:
        return redirect('login')

    if request.method == 'POST':
        uploaded_file = request.FILES.get('file')
        if uploaded_file:
            try:
                data = json.load(uploaded_file)
                for item in data:
                    title = item.get('title')
                    content = item.get('content')
                    if title and content:
                        UserData.objects.create(user=request.user, title=title, content=content)
                return redirect('data_list')
            except Exception as e:
                return render(request, 'import_json.html', {'error': '文件格式错误或内容不正确'})
        else:
            return render(request, 'import_json.html', {'error': '请上传一个文件'})

    return render(request, 'import_json.html')



def data_list(request):
    query = request.GET.get('q', '')
    if query:
        data = UserData.objects.filter(user=request.user, title__icontains=query)
    else:
        data = UserData.objects.filter(user=request.user)
    return render(request, 'data_list.html', {'data': data})




